import React from 'react'
import _ from 'underscore'
import $ from 'jquery'
import View from 'lib/View.jsx'
import Card from 'lib/components/card.jsx'
import ChartWidget from 'lib/components/ChartWidget.jsx'
import DefaultLoadingElement from 'lib/util/defaultLoadingElement.jsx'
import TraceGroupScope from './TraceGroupScope.es6'
import TraceView from './TraceView.jsx'
import format from 'lib/util/format'

var codeFormat = {
	html:function(str){
		var tagReg = /&lt;(\/)?\w*(\/)?&gt;/g;
		return str.replace(tagReg,function(tag){
			return '<span style="color:#E88004;font-weight:bold;">'+tag+'</span>'
		})
	},
	trace:function (str){
		var classReg = /(?!=\()[A-Z][^\(]+(?=\.)/,
			methodReg = /[^\.]*(?=\()/,
			fileNameReg = /(\().*(\))/,
			lineNumReg = /\d+(?=\))/;
		return str
			.replace(classReg,function(className){
				return '<span style="color:#E88004;font-weight:bold;">'+className+'</span>'
			})
			.replace(methodReg,function(methodName){
				return '<span style="color:red;">'+methodName+'</span>'
			})
			.replace(fileNameReg,function(fileName){
				return '<span style="color:green;">'+fileName+'</span>'
			})
			.replace(lineNumReg,function(lineNum){
				return '<span style="color:blue;">'+lineNum+'</span>'
			})
	}
}

export default class TraceGroupView extends View{
  render(){
    return (
      <div className="float-position-absolute">
        <div className="widget-float">
          <div className="widget-title">
            <a className="close iconfont" href="#/">&#xe638;</a>
            {this.state.trace?(
              <h4>
                {
                  this.state.trace.name
                }
              </h4>
            ):null}
          </div>
          {this.state.trace?this.renderDetail(this.state.trace):this.renderLoading()}
        </div>
      </div>
    )
  }
  renderLoading(){
    return (
      <div className="widget-content">
        <DefaultLoadingElement />
      </div>
    )
  }
  renderTraceDetail(detail){
    return (
      <div>
        <div className="pure-g">
          <div className="pure-u-1">
            <div className="box">
              <Card>
                <div className="trace-cross-title">
                  <span className="previous"
                    onClick={this.scope.showDetail.bind(this.scope,this.scope.traceOffset - 1)}>
                    <i className="iconfont">&#xe658;</i>
                  </span>
                  <strong>
                    {'第 '+(this.scope.traceOffset+1) + '/' + this.state.trace.count + ' 个同类HTTP错误'}
                    <span>{'发生时间：'+format.stampToTime(detail.timestamp)}</span>
                  </strong>
                  <span className="next"
                    onClick={this.scope.showDetail.bind(this.scope,this.scope.traceOffset + 1)}>
                    <i className="iconfont">&#xe659;</i>
                  </span>
                </div>
              </Card>
            </div>
          </div>
        </div>
        <div className="pure-g">
          <div className="pure-u-1">
            <div className="box">
              <Card>
                <div style={{paddingBottom: 15}}>URL：{ this.state.trace.url }</div>
                <div className="pure-g">
                  {
                    // (!BlueWare.isSaas)?(
                    //   <div className="pure-u-1 pure-u-lg-1-2">
                    //   设备信息：
                    //   {detail.manufacturerName+ ' ' +detail.modelName}
                    //   </div>
                    // ):null
                  }
                  <div className="pure-u-1 pure-u-lg-1-2">
                    应用版本：
                    {detail.appVersionName}
                  </div>
                  {
                    // (!BlueWare.isSaas)?(
                    //   <div className="pure-u-1 pure-u-lg-1-2">
                    //     内存占用：
                    //     {detail.memSize}
                    //   </div>
                    // ):null
                  }
                  <div className="pure-u-1 pure-u-lg-1-2">
                  操作系统：
                  {detail.osName + ' ' + detail.osVersionName}
                  </div>
                  {
                    // (!BlueWare.isSaas)?(
                    //   <div className="pure-u-1 pure-u-lg-1-2">
                    //   联网方式：
                    //   {detail.carrier}
                    //   </div>
                    // ):null
                  }
                </div>
              </Card>
            </div>
          </div>
        </div>
        <div className="pure-g">
          <div className="pure-u-1 pure-u-lg-1-2">
            {
              detail.httpRequestHeader.length?(
                <div className="box">
                  <Card>
                    <h4>Request Header</h4>
                    <ul>
                      {
                        detail.httpRequestHeader.map((p) => {
                          return (
                            <li key={p[0]}>{p[0]+'：'+p[1]}</li>
                          )
                        })
                      }
                    </ul>
                  </Card>
                </div>
              ):null
            }
            <div className="box">
              <Card>
                <h4>Response Header</h4>
                <ul>
                  {
                    detail.httpResponseHeader.map((p) => {
                      return (
                        <li key={p[0]}>{p[0]+'：'+p.slice(1).join(':')}</li>
                      )
                    })
                  }
                </ul>
                <hr />
                <h4>
                  {
                  'Response Body（'+
                  ((detail.params.custom_params&&detail.params.custom_params.content_type)? (detail.params.custom_params.content_type): '') + ';'+
                  ((detail.params.custom_params&&detail.params.custom_params.content_length)? (detail.params.custom_params.content_length+'Bytes'): '')+
                  '）'
                  }
                </h4>
                <div dangerouslySetInnerHTML={{__html:codeFormat.html(_.escape(detail.responseBody))}}></div>
              </Card>
            </div>
          </div>
          <div className="pure-u-1 pure-u-lg-1-2">
            <div className="box">
              <Card title="Stack Trace">
                <ul className="stack-trace">
                {
                  detail.trace.map(function(t, i){
                    return (
                      <li
                        key={i}
                        dangerouslySetInnerHTML={{
                          __html:codeFormat.trace(t)
                        }}
                        >
                      </li>
                    )
                  })
                }
                </ul>
              </Card>
            </div>
          </div>
        </div>
      </div>
    )
  }
  renderDetail(trace){
    return (
      <div className="widget-content error-trace-detail">
        <div className="pure-g">
          <div className="pure-u-1">
            <div className="box">
              <Card>
                <div className="pure-g">
                  <div className="pure-u-1 pure-u-xl-1-2">
                    <div className="pure-u-lg-1-2">
                      <span className="text-detail-label">状态码：</span>
                      <span className="text-detail-value">{trace.statusCode}</span>
                    </div>
                    <div className="pure-u-lg-1-2">
                      <span className="text-detail-label">最后发生时间：</span>
                      <span className="text-detail-value">{format.stampToTime(trace.lastTime)+' - '+format.duration(trace.lastTime)}</span>
                    </div>
                  </div>
                  <div className="pure-u-1 pure-u-xl-1-2">
                    <div className="pure-u-lg-1-2">
                      <span className="text-detail-label">同类错误数：</span>
                      <span className="text-detail-value">{trace.count}</span>
                    </div>
                    <div className="pure-u-lg-1-2">
                      <span className="text-detail-label">影响设备：</span>
                      <span className="text-detail-value">{trace.affected}</span>
                    </div>
                  </div>
                </div>
              </Card>
            </div>
          </div>
        </div>
        <div className="pure-g">
          <div className="pure-u-1 pure-u-lg-1-5">
            <div className="box">
              <Card title="地域">
                <ChartWidget store={this.state.pie2} chartType='pie'/>
              </Card>
            </div>
          </div>
          <div className="pure-u-1 pure-u-lg-1-5">
            <div className="box">
              <Card title="运营商">
                <ChartWidget store={this.state.pie0} chartType='pie'/>
              </Card>
            </div>
          </div>
          <div className="pure-u-1 pure-u-lg-1-5">
            <div className="box">
              <Card title="接入方式">
                <ChartWidget store={this.state.pie1} chartType='pie'/>
              </Card>
            </div>
          </div>
          <div className="pure-u-1 pure-u-lg-2-5">
            <div className="box">
              <Card title="错误次数">
                <ChartWidget store={this.state.chart} />
              </Card>
            </div>
          </div>
        </div>
        {
          this.state.detail?(
            this.renderTraceDetail(this.state.detail)
          ):null
        }
      </div>
    )
  }
}
TraceGroupView.defaultProps = {
  Scope:TraceGroupScope
}
